package org.lzuploader.gui.listeners.main;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.gui.WMain;
import org.lzuploader.model.Config;
import org.lzuploader.model.Localization;
import org.lzuploader.model.account.Account;
import org.lzuploader.model.account.AccountServerConfig;

/** This class is used when user selects a server on the main window.
 * 
 * @author Emmanuel Cron
 *
 */
public class ServerSelectionListener implements SelectionListener
{
    /** Logger of this class. */
    private static Log log = LogFactory.getLog(ServerSelectionListener.class);
    
    /** Localization of this class. */
    private static Localization localization = Localization.getInstance();
    
    /** This is used when default action is made on widget.
     * @param e Event that generated this action
     */ 
    @Override
    public void widgetDefaultSelected(final SelectionEvent e)
    {
        widgetSelected(e);
    }

    /** This is used when action is made on widget.
     * @param e Event that generated this action
     */ 
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
        log.debug("Selection has been made on server list.");
        
        Shell wMainShell = null;
        for (int i = 0 ; i < e.display.getShells().length ; i++)
        {
            if (e.display.getShells()[i].getData() instanceof WMain)
            {
                wMainShell = e.display.getShells()[i];
                break;
            }
        }
        
        final WMain main = (WMain) wMainShell.getData();
        
        log.trace("Saving new association.");
        
        if (!main.getServersList().getText().equals("<" + localization.getString("DROPDOWN_NEEDS_ACCOUNT") + ">") &&
            !main.getServersList().getText().equals("<" + localization.getString("DROPDOWN_NO_SERVER_FOUND") + ">")
        )
        {
            final Config config = Config.getInstance();
            
            final Account account = config.getAccounts().get(main.getAccountsList().getText());
            account.setServer(main.getServersList().getText());
            
            validateCurrentServerConfigAndCheckboxSelection(account, main.getSavePasswordCheckbox());
            
            config.getAccounts().put(account.getName(), account);
            config.save();
        }
        else
        {
            log.trace("Server name is invalid, I did not save association.");
        }
    }

    /**
     * Validates the current server selection configuration and checks the "save password" checkbox if needed.
     * This function will actually create a server configuration if the current server selection
     * configuration does not exist for this account. It will then check if the user asked
     * to save his password or not, and will check the box if needed;
     * @param account Account in which check if the server configuration exists.
     * @param savePassword The {@link Button} widget to check if needed.
     */
    public void validateCurrentServerConfigAndCheckboxSelection(final Account account, final Button savePassword)
    {
        if (account.getServerConfigs().containsKey(account.getServer()) == false)
        {
            log.trace("Server config does not exist, creating it: " + account.getServer());
            
            account.getServerConfigs().put(
                account.getServer(),
                new AccountServerConfig(account.getServer())
            );
        }
        
        log.trace("Enabling save password button and checking it if needed.");
        savePassword.setEnabled(true);
        savePassword.setSelection(account.getServerConfigs().get(account.getServer()).isAuthentificationSaveable());
    }
}
